/*
 * $Id: WebApplicationLifecycle.java 14 2014-08-15 11:50:17Z ratking $
 *
 * Copyleft (C) 2014 RatKing. All wrongs reserved.
 */
package cn.ratking.demo.jaws7.web;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.deltaspike.core.api.lifecycle.Destroyed;
import org.apache.deltaspike.core.api.lifecycle.Initialized;
import org.slf4j.Logger;

import cn.ratking.demo.jaws7.common.DateUtils;

/**
 * Web应用程序生命周期事件
 */
@ApplicationScoped
public class WebApplicationLifecycle implements Serializable {

    @Inject
    private transient Logger log;
    private Map<String, HttpSession> userMap = new LinkedHashMap<String, HttpSession>();
    private long beginTime;

    public Map<String, HttpSession> getUserMap() {
        return userMap;
    }

    public void setUserMap(Map<String, HttpSession> userMap) {
        this.userMap = userMap;
    }

    /**
     * 启动应用程序
     *
     * @param context Web应用程序
     */
    public void onCreateWebApp(@Observes @Initialized ServletContext context) {
        log.info("启动应用程序：" + context.getServletContextName());
        beginTime = System.currentTimeMillis();
    }

    /**
     * 关闭应用程序
     *
     * @param context Web应用程序信息
     */
    public void onDestroyWebApp(@Observes @Destroyed ServletContext context) {
        long endTime = System.currentTimeMillis();
        log.info("关闭应用程序：" + context.getServletContextName()
                + "，运行时间：" + DateUtils.getChineseTimeConsuming(endTime - beginTime));
    }

    /**
     * 创建会话
     *
     * @param session 会话
     */
    public void onCreateSession(@Observes @Initialized HttpSession session) {
        log.info("创建会话：" + session.getId());
        userMap.put(session.getId(), session);
    }

    /**
     * 销毁会话
     *
     * @param session 会话
     */
    public void onDestroySession(@Observes @Destroyed HttpSession session) {
        log.info("销毁会话：" + session.getId());
        userMap.remove(session.getId());
    }
}
